﻿var sys_mgr = {
    queuelist: [],
	connect_status:true,
	$queue_div:null,
    queue_panel: null,
    add_user_dlg:null,
	management_mode:false,
	selectQInst:null,
	current_queue:null,
	in_ops_page:null,
	out_ops_page:null,
	lostConnection:function(){
		sys_mgr.connect_status = false;
		sys_mgr.setTitle(sys_mgr.getLoginInfo() + "(离线)");
		$("div#mainpage h3#title").addClass("offline");
		$.each(sys_mgr.queuelist,function(index,Q){
			Q.lostConnection();
		});
	},
	setTitle:function(str){
		$("div#mainpage h3#title").text(str);
		//$("div#information h3#title").text(str);
		
		//$("div#in_queue_ops h3#title").text(str); <!--@-->
	},
	getLoginInfo:function(){
		return $("input#vendor_name").val() + "(" + $("input#login_name").val() + ")";
	},
	q_refresh:function(){
		$.getJSON(
			"/www/json_service.yaws?mod=queue&action=list",
			function(data){
				sys_mgr.queuelist = new Array();
				$("div#mainpage ul#queues_in").empty();
				$("div#mainpage ul#queues_out").empty();
				sys_mgr.queuelist = [];
				$.each(data.data,function(index,queue_info){
					q = new QueueInst(queue_info);
					q.refreshCusts();
					sys_mgr.queuelist.push(q);
				});
				$("div#mainpage ul#queues_in").listview("refresh");
				$("div#mainpage ul#queues_out").listview("refresh");
			}).error(function(){
				sys_mgr.lostConnection();
			});
	},
	findQbyId:function(id){
		var res = null;
		for(i = 0; i < sys_mgr.queuelist.length;i ++)
		{
			if(sys_mgr.queuelist[i].data.id == id){
				res = sys_mgr.queuelist[i];
				break;
			}
		}
		return res;
	},
	in_queue_click:function(evt){
		sys_mgr.current_queue = sys_mgr.findQbyId(evt.currentTarget.id);
		sys_mgr.current_queue.selected_cust = null;
	},
	out_queue_click:function(evt){
		sys_mgr.current_queue = sys_mgr.findQbyId(evt.currentTarget.id);
		if(sys_mgr.current_queue.custs.length == 0)
			evt.preventDefault();
		else{
			sys_mgr.current_queue.selected_cust = sys_mgr.current_queue.custs[0];
		}
	},
	in_queue_ops_show:function(evt,data){
		if(sys_mgr.current_queue != null){
			sys_mgr.in_ops_page.refresh(sys_mgr.current_queue,sys_mgr.connect_status);
		}else{
			$.mobile.changePage("#mainpage",{
					reverse:true	
					}
			);
		}
	},
	out_queue_ops_show:function(evt,data){
		if((sys_mgr.current_queue != null) && (sys_mgr.current_queue.selected_cust != null)){
			sys_mgr.out_ops_page.show($(data.prevPage).attr("id"));
		}else{
			$.mobile.changePage("#mainpage",{
					reverse:true	
					}
			);
		}
	},

	add_cust:function(ev){
		var data = {
			"name":$("#custom_info_fm #name").val() + "." + $("input:radio[name='name_title']:checked").val(),  //@--
			"mobile":$("#custom_info_fm #mobile").val(),
		};
		if($("#custom_info_fm").validate().element("#mobile") == false){
			$("#custom_info_fm #mobile").focus();
			return;
		}
		if(sys_mgr.connect_status == true){
			if(sys_mgr.current_queue != null){
				$.ajax({
					type:"POST",
					dataType:"json",
					content:"json",
					"data":JSON.stringify(data),
					url:"/www/json_service.yaws?mod=queue&action=add_cust&id=" + sys_mgr.current_queue.data.id,									
					success:function(data){
						if(data.result == "error"){
							showInformation(data.data);
						}else{
							data.new_tag = "new_cust";
							sys_mgr.current_queue.addCust(data);
							showInformation(
								"排队号:" + data.index.toString() + "前面还有" + data.loc.toString() + "位");
						}
					},
					error:function(){
						sys_mgr.lostConnection();
					}
				});
			}else{
				showInformation("请返回选择队列");
			}
		}else{
			showInformation("系统处于离线状态");
		}
		ev.preventDefault();
	},
	ui_refresh:function(){
		sys_mgr.q_refresh();
	},
	reset_service:function(evt){
		var password = $("#password",$(evt.currentTarget).parent()[0]).val();
		var vendor_id = $("input#vendor_id").val();
		var $dig_page = $("div#reset_confirm");
		$.getJSON(
			"/www/queue_act.yaws?mod=vendor&action=reset&id=" + vendor_id + "&password=" + password,
			function(data){
				$dlg_page.dialog('close')
			}
		);
		evt.preventDefault();
	}
};
function showInformation(info){
	$("div#information #info_area").text(info);
	$.mobile.changePage("#information",{
					transition:"slide",
					role:"dialog",} 
	);
}
function init_sys(){
	sys_mgr.in_ops_page = new InOpsPage("#in_queue_ops");
	sys_mgr.out_ops_page = new OutOpsPage("#out_queue_ops");
	sys_mgr.q_refresh();
	sys_mgr.setTitle(sys_mgr.getLoginInfo());
}
function load_queue($ui){
	sys_mgr.$queue_ui = $ui;
	sys_mgr.q_refresh();
}


/*******

    Class QueueInst, map to server-side queue-inst
*/
function QueueInst(data){
    var q_inst = this;
	this.data = data;
	this.selected_cust = null;
    this.custs = Array();
	this.in_ui = $("<li></li>")
				.attr("id",data.id)
				.addClass("in_queue")
				.append($("<a></a>")
					.text(data.name)
					.attr("href","#")
					.append($("<span></span>")
						.addClass("ui-li-count")
						.attr("id","count")

						.text("0"))
				)
				.appendTo($("div#mainpage ul#queues_in"));
	this.out_ui = $("<li></li>")
				.attr("id",data.id)
				.append($("<a></a>")
					.text(data.name)
					.attr("data-rel","dialog")
					.attr("data-close-btn","none")
					.attr("href","#")
					.append($("<span></span>")
						.attr("id","info")
						.addClass("ui-li-aside"))
				)
				.addClass("out_queue")
				.appendTo($("div#mainpage ul#queues_out"));
	
}
QueueInst.prototype.lostConnection = function(){
	$("a",this.out_ui).addClass("disabled");
	$("a",this.out_ui).removeAttr("href");
}
QueueInst.prototype.renderCusts = function(container){
	var q_inst = this;
	$.each(this.custs,function(index,C){
		q_inst.renderCust(C,container);
		C.new_tag = "old_cust";
	});
}
QueueInst.prototype.refresh = function(){
	$("span#count",this.in_ui).text(this.custs.length);

	$("a",this.in_ui).attr("href","#in_queue_ops");
	if(this.custs.length != 0){
		$("span#info",this.out_ui).text(this.custBrief(this.custs[0]));
		$("a",this.out_ui).attr("href","#out_queue_ops");
	}else{
		$("span#info",this.out_ui).text("空闲");
		$("a",this.out_ui).attr("href","#");
	}
}
QueueInst.prototype.custBrief = function(C){
	var res = this.data.prefix + C.index;
	if(C.name != undefined) res += " - " + C.name;
	if(C.mobile != undefined){
		if(C.mobile.length > 4){
			res += " - " + C.mobile.substr(C.mobile.length - 4 - 1,4);
		}else
		{
			res += " - " + C.mobile;
		}
	}
	return res;
}
QueueInst.prototype.refreshCusts = function(){
    var url =  "/www/json_service.yaws?mod=queue&action=detail&id=" + this.data.id;
    var q_inst = this;
    $.getJSON(url,function(data){
		$.each(data.data,function(index,C){
			C.new_tag = "old_cust";
			q_inst.addCust(C);
		});
		q_inst.refresh();
    });
}
QueueInst.prototype.addCust = function(Cust){
	var cust_ui;
	this.custs.push(Cust);
	this.refresh();
}
QueueInst.prototype.removeCust = function(C_Index){
	var temp = this.custs;
	var q_inst = this;
	this.custs = new Array();
	$.each(temp,function(index,C){
			if(C.index != C_Index)
				q_inst.custs.push(C);
		});
	this.refresh();
}

QueueInst.prototype.selectCust = function(C_Index){
	var q_inst = this;
	this.selected_cust = null;
	for(i = 0;i < this.custs.length; i ++){
		if(this.custs[i].index == C_Index){
			this.selected_cust = this.custs[i];
			break;
		}
	}
}

QueueInst.prototype.renderCust = function(C,container){
	var short_num;
	if(C.mobile.length >= 9){
		short_num = C.mobile.substring(C.mobile.length - 9,8);
	}else
	{
		short_num = "000000";
	}
	return $(container)
				.append($("<li></li>").append(
						$("<a></a>").text(this.data.prefix + C.index)
									.addClass("out_link")
									.attr("data-rel","dialog")
									.attr("data-role","button")
									.attr("data-close-btn","none")
									.attr("href","#out_queue_ops")
					).addClass("cust_select").attr("id",C.index).addClass(C.new_tag)
				);
	//return $("<li></li>").append(vsprintf("%-6.6s %-8.8s %-8.8s %-4.4d",[(this.data.prefix + C.index), short_num, C.name,C.sms_sent_times])).data("id",C.index);
}

QueueInst.prototype.renderCustBrief = function(C){
	return $("<dd></dd>").append(this.data.prefix + C.index + "  " + C.mobile + "   " + C.name + "  " + C.sms_sent_times).data("id",C.index);
}
QueueInst.prototype.renderCustTableItem = function(C){
	var short_num;
	if(C.mobile.length >= 9){
		short_num = C.mobile.substring(C.mobile.length - 9,8);
	}else
	{
		short_num = "XXXX";
	}
	return $("<tr></tr>").addClass("item").append(vsprintf("<td>%s</td> <td>%s</td> <td>%s</td> <td>%4d</td>",[(this.data.prefix + C.index), short_num, C.name,C.sms_sent_times])).data("id",C.index);
}

/*
obsolete it
*/
QueueInst.prototype.refreshCustUI = function($cust_area)
{
	var C;
	var q_inst = this;
	$(".cust_list",$cust_area).empty();
	$.each(this.custs,function(index,C){
		//$("div.cust_content",q_inst.ui).append(q_inst.renderCust(C));
		q_inst.renderCust(C).appendTo($(".cust_list",$cust_area));
	});
}
QueueInst.prototype.findCustByIndex = function(index){
	var cust = undefined;
	for(i = 0;i < this.custs.length;i++){
		if(this.custs[i].index == index){
			cust = this.custs[i];
			break;
		}
	}
	return cust;
}
QueueInst.prototype.removeSelectedCust = function(reason,cb){
	if(this.selected_cust != null)
		this.requestRemoveCustAction(this.selected_cust.index,reason,cb);
}
QueueInst.prototype.requestRemoveCustAction = function(cust_index,tag,cb){	
			var q_inst = this;
			$.ajax({
				url:"/www/queue_act.yaws?mod=queue&action=del_cust&id=" + this.data.id + "&cust_id=" + cust_index + "&tag=" + tag,
				context:this
			}).done(function(data){
				q_inst.removeCust(cust_index);
				cb(data);
				});
}
function InOpsPage($page){
	this.page = $page;
	this.mobile_invalid = "unknown";
	this.last_phone = "";
}
InOpsPage.prototype.refresh = function(Q,con_status){
	this.mobile_invalid = "unknown";
	this.last_phone = "";
	$("#custom_info_fm").validate().element("#mobile"); //bad code
	

	this.queue = Q;
	$("#name",this.page).val("");
	$("#mobile",this.page).val("");
	$("#title",this.page).text(Q.data.name);
	$("#cust_list",this.page).empty();
	Q.renderCusts($("#cust_list",this.page));
	$("#cust_list .cust_select",this.page).click(function(evt){
		Q.selectCust(evt.currentTarget.id);
	});
	
	$("#cust_counter",this.page).text(Q.custs.length);
	$("#cust_list",this.page).listview("refresh");
	if(con_status == false){
		$("#cust_list a",this.page).removeAttr("href");
	}
}

function OutOpsPage($page){
	this.page = $page;
}
OutOpsPage.prototype.show = function(prevPageId){
	var thisPage = this;
	this.queue = sys_mgr.current_queue;
	this.prevPageId = prevPageId;
	$("#title",this.page).text(this.queue.data.name); //todo cust info
	$( "#info_area",this.page).text(vsprintf("顾客%6s(%6s)",[
		(this.queue.data.prefix + this.queue.selected_cust.index), 
		this.queue.selected_cust.name]));
	$("div#out_queue_ops .out_ops_bt").click(function(evt){
				thisPage.queue.removeSelectedCust(evt.currentTarget.id,function(data){
				  //	$(thisPage.page).dialog('close')
					//	$.mobile.changePage(thisPage.prevPageId,{reverse:true});
				});
	});
}